package com.tsingteng.cosfun.ui.cosfun;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.DialogListener;
import com.tsingteng.cosfun.bean.AttentFansbean;
import com.tsingteng.cosfun.bean.BaseBackBean;
import com.tsingteng.cosfun.bean.CommBean;
import com.tsingteng.cosfun.callback.AppListener;
import com.tsingteng.cosfun.common.BroadcastManager;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.ui.cosfun.adapter.CommListAdapter;
import com.tsingteng.cosfun.ui.cosfun.contract.CommContract;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverListener;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.ObserverManager;
import com.tsingteng.cosfun.ui.cosfun.cosinterface.RecyclerOnScrollListener;
import com.tsingteng.cosfun.ui.cosfun.presenter.CommPresenter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.dialog.BaseBottomSheetFragment;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.tsingteng.cosfun.widget.dialog.CommSelectDialog;
import com.tsingteng.cosfun.widget.dialog.CommentDialog;

import java.util.ArrayList;
import java.util.List;

public class CommentListDialogFragment extends BaseBottomSheetFragment implements CommContract.ICommView, CommListAdapter.OnItemClickListener, ObserverListener, CommSelectDialog.OnItemClickListener
        , DialogListener {

    // TODO: Customize parameter argument names
    private static final String ARG_ITEM_COUNT = "item_count";
    private CommPresenter commPresenter = null;
    private int pageNo = 1;
    private List<CommBean.CommData> commList = null;
    private CommListAdapter commListAdapter = null;
    private String workId = "";
    private RecyclerView recyclerView = null;
    private TextView empty_tv;
    private TextView comm_count = null;
    private CommLisenter commLisenter = null;
    private int opus_position;//当前作品下标
    private int profileId;
    private String mNickname;
    private int totalCount = 0;
    private RelativeLayout mTopRel;

    // TODO: Customize parameters
    public static CommentListDialogFragment newInstance() {
        final CommentListDialogFragment fragment = new CommentListDialogFragment();
        final Bundle args = new Bundle();
        args.putInt(ARG_ITEM_COUNT, 20);
        fragment.setArguments(args);
        return fragment;
    }

    public void setParam(int position, String workId, int mProfileId, String profileName) {
        this.workId = workId;
        this.opus_position = position;
        this.profileId = mProfileId;
        this.mNickname = profileName;

    }

    //评论成功 回调首页更新数量
    public void setCommLisenter(CommLisenter commLisenter) {
        this.commLisenter = commLisenter;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里将view的高度设置为精确高度，即可屏蔽向上滑动不占全屏的手势。
        View view = inflater.inflate(R.layout.fragment_comment_dialog, container, false);
//        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//                AppUtils.getScreenWidthAndHeight(getActivity())[1] / 5 * 2));
        commPresenter = new CommPresenter(this);
        commList = new ArrayList<>();
        ObserverManager.getInstance().add(this);
        return view;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mTopRel = view.findViewById(R.id.top_rel);
        recyclerView = view.findViewById(R.id.comm_recycler);
        empty_tv = view.findViewById(R.id.comm_empty);
        comm_count = view.findViewById(R.id.comm_count);
        ImageView close_img = view.findViewById(R.id.comm_close);
        TextView at = view.findViewById(R.id.comm_at);
        at.setText("@");
        commListAdapter = new CommListAdapter(getActivity(), commList, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(commListAdapter);
        commListAdapter.notifyDataSetChanged();
        EditText et = (EditText) view.findViewById(R.id.comm_et);
        close_img.setOnClickListener(v -> dismiss());
        et.setOnClickListener(v -> {
//                Intent intent = new Intent(getActivity(), CommInputActivity.class);
//                intent.putExtra("workId", workId);
//                intent.putExtra("commId", "");
//                startActivity(intent);
            if (LogonUtils.getIsLogin()) {
                showCommentDialog(-1, workId, "", null);
            } else {
                Navigate.startLogon(getContext(), false, 0);
            }


        });

        view.findViewById(R.id.comm_at).setOnClickListener(v -> {
            AtFragment atFragment = AtFragment.newInstance();
            atFragment.setOnItemSelectLisenter(data -> {
                showCommentDialog(-1, workId, "", data);
                atFragment.dismiss();
            });
            if (null == getActivity()){
                return;
            }
            atFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
        });
        mTopRel.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                dismiss();
                return true;
            }
        });


        recyclerView.addOnScrollListener(onScrollListener);
        setState(CommListAdapter.FooterState.Normal);
        commPresenter.getOpusCommList("", "1", workId, pageNo + "", Config.PAGE_SIZE + "", "");

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }


    protected CommListAdapter.FooterState mState = CommListAdapter.FooterState.Normal;

    protected void setState(CommListAdapter.FooterState mState) {
        this.mState = mState;
        changeAdaperState();
    }

    //改变底部bottom的样式
    protected void changeAdaperState() {
        if (commListAdapter != null && commListAdapter.mFooterHolder != null) {
            commListAdapter.mFooterHolder.setStatus(mState);
        }
    }

    RecyclerOnScrollListener onScrollListener = new RecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (commListAdapter.mFooterHolder.status == CommListAdapter.FooterState.TheEnd) {
                return;
            }
            commPresenter.getOpusCommList("", "1", workId, pageNo + "", Config.PAGE_SIZE + "", "");

            setState(CommListAdapter.FooterState.Loading);
        }
    };


    @Override
    public void successStatus(BaseBackBean baseBackBean) {

    }

    @Override
    public void succeed(CommBean commBean) {
        commList.addAll(commBean.getCommentList());
        commListAdapter.setAuthorId(commBean.getAuthorId());
        commListAdapter.notifyDataSetChanged();
        if (commList.size() == 0) {
            recyclerView.setVisibility(View.INVISIBLE);
            empty_tv.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            empty_tv.setVisibility(View.INVISIBLE);
            if (commBean.getCommentList() == null || commBean.getCommentList().size() == 0) {
                setState(CommListAdapter.FooterState.TheEnd);
            }
            if (commList.size() < Config.PAGE_SIZE) {
                setState(CommListAdapter.FooterState.TheEnd);
            } else {
                pageNo++;
            }

        }
        totalCount = commBean.getTotal();
        String mTotalCount = StringUtils.formatZanCount(totalCount);
        AppListener.OnCommentTotalListener listener =AppListener.getInstance().getCommentTotalListener();
        if (null !=listener){
            listener.onCommonet(mTotalCount);
        }
        String comment = "评论 " + mTotalCount;
        comm_count.setText(comment);
    }

    @Override
    public void failure(int code, String error) {

    }

    @Override
    public void showCancelPullBlack(int data) {
        if (1 == data) {
            ToastUtils.showToast(getResources().getString(R.string.cancel_black_success));
        }
    }

    @Override
    public void onItemClick(int position, String commId) {
        final int index = position;
        if (commList.get(position).getCommentUserId() == LogonUtils.getProFildId()) {
            List<String> list = new ArrayList<>();
            list.add("删除");
            BottomListDialog bottomListDialog = new BottomListDialog(getActivity());
            bottomListDialog.setList(list);
            bottomListDialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
                @Override
                public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                    deleteComm(index);
                }

                @Override
                public void onClickBottom() {

                }
            });
            bottomListDialog.show();
        } else {
//            dialog = builder.setMessage(position, workId, commId, "").setItemClickListener(this).createDialog();
//            dialog.show();
            int proFildId = LogonUtils.getProFildId();
            if (profileId == proFildId) {
                List<String> list = new ArrayList<>();
                list.add("回复并置顶");
                list.add("回复");
                list.add("举报");
                BottomListDialog bottomListDialog = new BottomListDialog(getActivity());
                bottomListDialog.setList(list);
                bottomListDialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
                    @Override
                    public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                        if (position ==0){
                            showCommentDialog(1,index, workId, commId, null);
                        }else if (position == 1) {
                            showCommentDialog(index, workId, commId, null);
                        } else if (position == 2) {
                            int type = 3;
                            Navigate.startReportList(getContext(), type, Integer.parseInt(commId));
                        }
//                    deleteComm(index);
                    }

                    @Override
                    public void onClickBottom() {

                    }
                });
                bottomListDialog.show();
            }else {
                List<String> list = new ArrayList<>();
                list.add("回复");
                list.add("举报");
                BottomListDialog bottomListDialog = new BottomListDialog(getActivity());
                bottomListDialog.setList(list);
                bottomListDialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
                    @Override
                    public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                      if (position == 0) {
                            showCommentDialog(index, workId, commId, null);
                        } else if (position == 1) {
                            int type = 3;
                            Navigate.startReportList(getContext(), type, Integer.parseInt(commId));
                        }
//                    deleteComm(index);
                    }
                    @Override
                    public void onClickBottom() {

                    }
                });
                bottomListDialog.show();
            }


        }

    }

    @Override
    public void onLikeClick(int position, String commId, String type) {//评论点赞
        commPresenter.getCommlike(commId, "", commId, type);
        if ("1".equals(type)) {
            commList.get(position).setIslike(1);
            commList.get(position).setLikeTimes((commList.get(position).getLikeTimes() + 1));
        } else {
            commList.get(position).setLikeTimes((commList.get(position).getLikeTimes() - 1));
            commList.get(position).setIslike(0);
        }
        commListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onUserClick(String userId) {
        Bundle bundle = new Bundle();
        bundle.putInt("user_id", Integer.parseInt(userId));
        bundle.putInt("tag", 1);
        TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
        dismiss();
    }

    @Override
    public void observerUpData(int eventType, int index, int id) {
        if (eventType == EVENT_COMM_SUCCESS) {
            commList.clear();
            commPresenter.getOpusCommList("", "1", workId, pageNo + "", Config.PAGE_SIZE + "", "");
        }
    }

    @Override
    public void onAnswer(int position, String opusId, String commId, String userId) {
//        Intent intent = new Intent(getActivity(), CommInputActivity.class);
//        intent.putExtra("workId", workId);
//        intent.putExtra("commId", commId);
//        startActivity(intent);

        showCommentDialog(position, workId, commId, null);
    }

    @Override
    public void onReport(int position, String opusId, String commId, String userId) {
        int type = 3;
        Navigate.startReportList(getContext(), type, Integer.parseInt(commId));
    }

    private void showCommentDialog(int top,int position, String workId, String commId, AttentFansbean.Data data) {
        if (null == getActivity()){
            return;
        }
        CommentDialog mCommentDialog = new CommentDialog(top,position, workId, commId, data, (position1, commId1, commStr) -> {
            LogUtils.e("testcomm", "评论成功  position=" + position1);
            showNewComm(position1, commId1, commStr);
        }, this);
        mCommentDialog.setAttentData(profileId, mNickname);
        mCommentDialog.show(getActivity().getSupportFragmentManager(), "comment");
    }
    private void showCommentDialog(int position, String workId, String commId, AttentFansbean.Data data) {
        if (null == getActivity()){
            return;
        }
        CommentDialog mCommentDialog = new CommentDialog(position, workId, commId, data, (position1, commId1, commStr) -> {
            LogUtils.e("testcomm", "评论成功  position=" + position1);
            showNewComm(position1, commId1, commStr);
        }, this);
        mCommentDialog.setAttentData(profileId, mNickname);
        mCommentDialog.show(getActivity().getSupportFragmentManager(), "comment");
    }

    private void showNewComm(int position, String commId, String commStr) {
        CommBean.CommData commData = new CommBean.CommData();
        if (position == -1) {
            commData.setCommentUserShot(LogonUtils.getNickIcon());
            commData.setCommentUserName(LogonUtils.getNickName());
            commData.setLikeTimes(0);
            commData.setCommentId(commId);
            commData.setCommentText(commStr);
            commData.setCommentTime(System.currentTimeMillis() / 1000);
            commData.setCommentUserId(LogonUtils.getProFildId());
        } else {
            CommBean.CommData c = commList.get(position);
            commData.setLikeTimes(0);
            commData.setCommentId(commId);
            commData.setCommentUserShot(LogonUtils.getNickIcon());
            commData.setCommentUserName(LogonUtils.getNickName());
            commData.setCommentText(commStr);
            commData.setCommentUserId(LogonUtils.getProFildId());
            commData.setCommentTime(System.currentTimeMillis() / 1000);
            commData.setParentCommentId(c.getCommentId());
            commData.setParentCommentText(c.getCommentText());
            commData.setParentCommentUserName(c.getCommentUserName());
            commData.setParentCommentUserShot(c.getCommentUserShot());
        }
        commList.add(0, commData);

        LogUtils.e("testcomm", "commList.size=" + commList.size());
        for (CommBean.CommData d : commList) {
            LogUtils.e("testcomm", "d" + d.toString());
        }
        if (commLisenter != null) {
            commLisenter.commSuccess(opus_position, 1);
        }
        totalCount++;
        String mTotalCount ="评论 " + StringUtils.formatZanCount(totalCount) ;
        comm_count.setText(mTotalCount);
        commListAdapter.notifyDataSetChanged();
        if (commList.size() == 0) {
            recyclerView.setVisibility(View.INVISIBLE);
            empty_tv.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            empty_tv.setVisibility(View.INVISIBLE);
            if (commList.size() < Config.PAGE_SIZE) {
                setState(CommListAdapter.FooterState.TheEnd);
            }
        }

    }

    //删除自己的评论
    private void deleteComm(int position) {
        if (position < commList.size()) {
            CommBean.CommData commData = commList.remove(position);
            commPresenter.commDel(commData.getCommentId());

            totalCount--;
            String mTotalCount = "评论 " + StringUtils.formatZanCount(totalCount);
            comm_count.setText(mTotalCount);
            commListAdapter.notifyDataSetChanged();
            if (commLisenter != null) {
                commLisenter.commSuccess(opus_position, 0);
            }
        }
        if (commList.size() == 0) {
            recyclerView.setVisibility(View.INVISIBLE);
            empty_tv.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            empty_tv.setVisibility(View.INVISIBLE);

        }
    }

    @Override
    public void clickDialog(long workId) {
        commPresenter.getCancelPullBlack(workId);
    }

    public interface CommLisenter {
        void commSuccess(int position, int type);
    }
}
